package com.zhiwang.planet.util

import com.zhiwang.planet.exception.ExpiredException
import com.zhiwang.planet.exception.XQException
import com.zhiwang.planet.mvvm.model.ResponseWrapper
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext

fun CoroutineScope.launchDelayError(context: CoroutineContext = EmptyCoroutineContext,
                                    start: CoroutineStart = CoroutineStart.DEFAULT,
                                    errHandler: ((Throwable) -> Unit)?,
                                    block: suspend CoroutineScope.() -> Unit) {

    launch(context, start) {

        try {
            block()

        } catch (e: Exception) {
            errHandler?.let { it(e) }
        }

    }

}


suspend fun <T> withApiContext( block: suspend () -> ResponseWrapper<T>): T {
    val res = withContext(Dispatchers.IO) { block() }

    if (res.isOk())
        return res.data
    else if (res.isAuthExpired())
        throw ExpiredException(res.errMsg)
    else throw XQException(res.errMsg)
}